<?php
/**
 * Loads files
 *
 *
 */
namespace PUF;

class Loader {
	/**
	 * Loader. Contains the only instance
	 */
	private static $instance = null;
	
	/**
	 * Returns the only instance
	 */
	public static function getInstance() {
		if (!self::$instance) {
			self::$instance = new Loader();
		}
		
		return self::$instance;
	}
	
	/**
	 * Loads the selected files
	 *
	 * Params:
	 * $files : Array. Files to be loaded. Accepts a string if it's only one file.
	 *		Only the name of the class, they will be appended .php at the end.
	 * $options : Array. Posible values:
	 * 		'type' => ['lib' | 'controller' | 'model']
	 *			// Default 'lib'
	 */
	public function load($files, $options = array()) {
		if (!$files) {
			throw new \Exception(__METHOD__ . '() => No files selected!');
		}
		
		arrayizeObject($files);
		
		$defaultOptions = array (
			'type'	=> 'lib'
		);
		
		$options = array_merge($defaultOptions, $options);
			
		if (isset($options['vars'])) {
			foreach ($options['vars'] as $key => $var) {
				$$key = $var;
			}
		}
		
		foreach ($files as $file) {
			switch ($options['type']) {
				case 'lib':			$location = "{$file}.php";
									break;
				case 'plugin':		$location = "plugins/{$file}/{$file}.php";
									break;
				case 'config':		$location = "../config/{$file}.php";
									break;
				case 'controller':	if (isset($options['plugin'])) {
										$options['type'] = "Plugin\\{$options['plugin']}\\{$options['type']}";
										$location = "plugins/{$options['plugin']}/controllers/{$file}.php";
									} else {
										$location = "../controllers/{$file}.php";
									}
									break;
				case 'model':		if (isset($options['plugin'])) {
										$options['type'] = "Plugin\\{$options['plugin']}\\{$options['type']}";
										$location = "plugins/{$options['plugin']}/models/{$file}.php";
									} else {
										$location = "../models/{$file}.php";
									}
									break;
				case 'view':		$location = "../views/{$file}.php";
									break;
			}
			
			$location = dirname(__FILE__) . '/' . $location;
			
			if (file_exists($location)) {
				include($location);
			} else {
				if (!isset($options['required']) || $options['required']) {
					throw new \Exception(
						__METHOD__ . '() => ' . ucfirst($options['type'])
						. " file '{$file}' does not exist!"
					);
				}
			}
		}
	}
}